﻿using Microsoft.AspNetCore.Http;
using Qiniu.Http;
using Qiniu.Storage;
using Qiniu.Util;
using System.Net.Http.Headers;


namespace Public_Class_Library
{
    /// <summary>
    /// 上传文件类
    /// </summary>
    public static class FileHelper
    {
        /// <summary>  
        /// 上传文件到七牛云  
        /// </summary>  
        /// <param name="formFile">本地文件路径</param>  
        /// <param name="key">在七牛云上的文件名</param>  
        /// <returns>上传结果</returns>  
        public static HttpResult UploadFile(IFormFile file)
        {
            try
            {
                // 定义常量
                const string accessKey = "cnyF14f4ayJfqNf8Wgj3aXT5Q_c_A77hZPZnUaV9";
                const string secretKey = "u2zDkwWgN_DyoJnEVrMpoc_3qD7GDcD8PtE7PKIU";
                // 输入秘钥
                Mac mac = new Mac(accessKey, secretKey);
                // 创建上传配置  
                Config config = new Config();
                // 使用Zone0作为上传区域，你可以根据需要更改  
                config.Zone = Zone.ZONE_CN_East;
                // 初始化上传管理对象  
                FormUploader formuploader = new FormUploader(config);
                // 调用SDK上传文件  
                try
                {
                    //打开文件流
                    using (Stream? stream = file.OpenReadStream())
                    {
                        // 生成上传凭证  
                        PutPolicy putPolicy = new PutPolicy();
                        // 七牛云空间名称
                        putPolicy.Scope = "ouyangxi";
                        // 生成上传凭证  
                        string upToken = Auth.CreateUploadToken(mac, putPolicy.ToJsonString());
                        // 保留原始文件名（包含扩展名）  
                        string key = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
                        // 创建HttpResult对象用于存储上传结果 
                        HttpResult result = formuploader.UploadStream(stream, key, upToken, null);
                        // 返回上传结果  
                        return result;
                    }
                }
                catch (Exception ex)
                {
                    // 处理其他异常  
                    Console.WriteLine("上传文件发生异常: {0}", ex.Message);
                    throw;
                }
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>  
        /// 从七牛云下载文件-注意：是异步方法
        /// </summary>  
        /// <param name="fileName">文件名</param>  
        /// <param name="localFilePath">本地保存路径</param>  
        /// <returns>一个表示操作是否成功的布尔值</returns>  
        public static async Task<bool> DownloadFileAsync(string fileName)
        {
            try
            {
                // 构建下载链接  
                var downloadUrl = $"http://sap3wa8r6.hd-bkt.clouddn.com/{fileName}";
                //下载的文件目录
                const string targetDirectory = @"D:\下载";

                // 使用 HttpClient 来执行下载  
                using (var httpClient = new HttpClient())
                {
                    var response = await httpClient.GetAsync(downloadUrl);

                    if (response.IsSuccessStatusCode)
                    {
                        // 构建本地保存文件的完整路径，包括文件名  
                        var localFilePath = Path.Combine(targetDirectory, fileName);
                        // 确保本地目录存在  
                        var directory = Path.GetDirectoryName(localFilePath);
                        if (!Directory.Exists(directory))
                        {
                            Directory.CreateDirectory(directory);
                        }

                        // 将文件内容写入到本地文件  
                        using (var stream = await response.Content.ReadAsStreamAsync())
                        using (var fileStream = File.Create(localFilePath))
                        {
                            await stream.CopyToAsync(fileStream);
                        }

                        return true; // 下载成功  
                    }
                    else
                    {
                        Console.WriteLine($"下载失败，状态码：{response.StatusCode}");
                        return false; // 下载失败  
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"下载时发生异常：{ex.Message}");
                throw; // 重新抛出异常  
            }
        }
    }
}